package imwallet.dichen.com.library.framework;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.MenuRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import imwallet.dichen.com.library.app.App;
import imwallet.dichen.com.library.bean.User;
import imwallet.dichen.com.library.constant.Constant;
import imwallet.dichen.com.library.utils.ACache;
import imwallet.dichen.com.library.utils.ActivityManager;
import imwallet.dichen.com.library.utils.LogUtils;
import imwallet.dichen.com.library.utils.SoftHideKeyBoardHelper;
import imwallet.dichen.com.library.widget.DefaultToolbar;
import imwallet.dichen.com.library.widget.LoadingDialog;
import imwallet.dichen.com.library.widget.LoadingView;

/**
 *
 * @author Administrator
 * @date 2018/5/24
 */

public abstract class BaseActivity extends AppCompatActivity {
    public final String TAG = getClass().getName();
    private ViewGroup.LayoutParams mLayoutParams;
    private LoadingDialog mLoadingDialog;
    /**
     * 视图变化前的可用高度
     */
    private int usableHeightPrevious = 0;
    private LinearLayout mContentView;
    private LoadingView mLoadingView;
    protected DefaultToolbar mToolbar;
    private Lifecycle mLifecycle;
    private View mViewObserved;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = new LinearLayout(this);
        ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT,
                ViewGroup.MarginLayoutParams.MATCH_PARENT);
        mContentView.setLayoutParams(params);
        mContentView.setOrientation(LinearLayout.VERTICAL);
        super.setContentView(mContentView);
        if(mLifecycle != null) {
            mLifecycle.onCreate(TAG);
            if(App.get().isDebug()) {
                LogUtils.e(TAG, "---onCreate---");
            }
        }
        ActivityManager.get().put(this);
        SoftHideKeyBoardHelper.assistActivity(this);
        setTransparentBar();
    }

    /**
     * 配置状态栏
     */
    private void setTransparentBar() {
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //透明状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    protected int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mLifecycle != null) {
            mLifecycle.onResume(TAG);
            if(App.get().isDebug()) {
                LogUtils.e(TAG, "---onResume---");
            }
        }
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        View view = LayoutInflater.from(this).inflate(layoutResID, null);
        setContentView(view);
    }

    @Override
    public void setContentView(View view) {
        if(view != null) {
            mContentView.removeAllViews();
            if(showToolbar()) {
                mToolbar = new DefaultToolbar(this);
                mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onNavigationClick();
                    }
                });
                mContentView.addView(mToolbar);
            } else if(createToolbar() != null) {
                mContentView.addView(createToolbar());
            }
            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            view.setLayoutParams(params);
            mContentView.addView(view);
        } else {
            throw new RuntimeException("初始化布局错误~");
        }
        initView();
        initData();
        initListener();
    }

    protected void initListener() {

    }

    protected void initData() {

    }

    protected void initView() {

    }

    public void showLoadingDialog() {
        showLoadingDialog("");
    }

    public void showLoadingDialog(String title) {
        if(mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this);
        }
        mLoadingDialog.setMessage(title);
        dismissLoadingDialog();
        mLoadingDialog.show();
    }

    protected void dismissLoadingDialog() {
        if(mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    final protected void setNavigationIcon(@DrawableRes int resId) {
        if(mToolbar != null) {
            mToolbar.setNavigationIcon(resId);
        }
    }

    /**
     * 显示加载布局隐藏其他布局
     */
    public void showLoadingView() {
        if(mLoadingView == null) {
            mLoadingView = new LoadingView(this);
        }
        int index;
        if(mToolbar != null || createToolbar() != null) {
            index = 1;
        } else {
            index = 0;
        }
        for(int i = index; i < mContentView.getChildCount(); i ++) {
            mContentView.getChildAt(i).setVisibility(View.GONE);
        }
        mContentView.addView(mLoadingView, index);
    }

    /**
     * 隐藏加载布局
     */
    public void hideLoadingView() {
        if(mLoadingView == null) {
            return;
        }
        mContentView.removeView(mLoadingView);
        for(int i = 0; i < mContentView.getChildCount(); i ++) {
            mContentView.getChildAt(i).setVisibility(View.VISIBLE);
        }
    }

    public boolean showToolbar() {
        return true;
    }

    public Toolbar createToolbar() {
        return null;
    }

    public void setTitle(String title) {
        if(mToolbar !=null && !TextUtils.isEmpty(title)) {
            mToolbar.setTitle(title);
        }
    }

    public void setTitle(String title, boolean showBack) {
        if(mToolbar !=null && !TextUtils.isEmpty(title)) {
            mToolbar.setTitle(title);
            if(!showBack) {
                mToolbar.getNavigationImage().setVisibility(View.GONE);
            }
        }
    }

    @SuppressLint("ResourceType")
    public void inflateMenu(@MenuRes int resId) {
        if(mToolbar != null && resId > 0) {
            mToolbar.inflateMenu(resId);
            if(mToolbar.getMenu() != null) {
                mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        onMenuClick(item.getActionView(), item.getItemId());
                        return true;
                    }
                });
            }
        }
    }

    public void setMenuTitle(String text) {
        if(!TextUtils.isEmpty(text) && mToolbar != null) {
            mToolbar.setMenuText(text);
            if(mToolbar.getMenuView() != null) {
                mToolbar.getMenuView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onMenuClick(view, view.getId());
                    }
                });
            }
        }
    }

    @SuppressLint("ResourceType")
    public void setMenuImage(@DrawableRes int resId) {
        if(mToolbar != null && resId > 0) {
            mToolbar.setMenuImage(resId);
            if(mToolbar.getMenuView() != null) {
                mToolbar.getMenuView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onMenuClick(view, view.getId());
                    }
                });
            }
        }
    }

    protected void pushFragment(Class<? extends Fragment> clazz) {
        pushFragment(clazz, null, true);
    }

    protected void pushFragment(Class<? extends Fragment> clazz, Bundle bundle) {
        pushFragment(clazz, bundle, true);
    }

    /**
     * 打开fragment
     *
     * @param clazz
     * @param bundle
     * @param isAddToBackStack
     */
    protected void pushFragment(Class<? extends Fragment> clazz, Bundle bundle, boolean isAddToBackStack) {
        Intent intent = new Intent(this, RouterActivity.class);
        intent.putExtra(RouterActivity.KEY_TARGET, clazz);
        intent.putExtra(RouterActivity.KEY_DATA, bundle);
        intent.putExtra(RouterActivity.KEY_TYPE, RouterActivity.TYPE_PUSH);
        startActivity(intent);
    }

    /**
     * 切换fragment
     *
     * @param clazz
     */
    protected void switchFragment(Class<? extends Fragment> clazz) {
        Intent intent = new Intent(this, RouterActivity.class);
        intent.putExtra(RouterActivity.KEY_TARGET, clazz);
        intent.putExtra(RouterActivity.KEY_TYPE, RouterActivity.TYPE_SWITCH);
        startActivity(intent);
    }

    public void onNavigationClick() {
        onBackPressed();
    }

    public void onMenuClick(View view, int id) {

    }

    public void setLifecycle(Lifecycle lifecycle) {
        mLifecycle = lifecycle;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mLifecycle != null) {
            mLifecycle.onPause(TAG);
            if(App.get().isDebug()) {
                LogUtils.e(TAG, "---onPause---");
            }
        }
    }

    /**
     * 设置toolbar 背景颜色
     *
     * @param color
     */
    public void setToolbarBackground(@ColorInt int color) {
        if(mToolbar != null) {
            mToolbar.setBackgroundColor(color);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLifecycle != null) {
            mLifecycle.onDestory(TAG);
            if(App.get().isDebug()) {
                LogUtils.e(TAG, "---onDestroy---");
            }
        }
        mLifecycle = null;
        ActivityManager.get().remove(this);
//        RefWatcher refWatcher = App.getRefWatcher(this);
//        refWatcher.watch(this);
    }

    /**
     * 跳转到App设置页面修改权限
     */
    protected void gotoSetting() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(localIntent);
    }

    /**
     * 检测是否登录
     *
     * @return
     */
    final protected boolean checkLogin() {
        Object object = ACache.get(this).getAsObject(Constant.Cache.KEY_USER);
        return object != null && object instanceof User;
    }

    /**
     * 切换密码显示和隐藏
     *
     * @param isShow
     * @param view
     */
    final protected void switchPassword(boolean isShow, EditText view) {
        if (isShow){
            // 输入为密码且可见
            view.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }else {
            // 设置文本类密码（默认不可见），这两个属性必须同时设置
            view.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
        }
    }

    private void AndroidWorkaround(View viewObserving) {
        mViewObserved = viewObserving;
        //给View添加全局的布局监听器
        mViewObserved.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                resetLayoutByUsableHeight(computeUsableHeight());
            }
        });
        mLayoutParams = mViewObserved.getLayoutParams();
    }

    private void resetLayoutByUsableHeight(int usableHeightNow) {
        //比较布局变化前后的View的可用高度
        if (usableHeightNow != usableHeightPrevious) {
            //如果两次高度不一致
            //将当前的View的可用高度设置成View的实际高度
            mLayoutParams.height = usableHeightNow;
            mViewObserved.requestLayout();//请求重新布局
            usableHeightPrevious = usableHeightNow;
        }
    }

    /**
     * 计算视图可视高度
     *
     * @return
     */
    private int computeUsableHeight() {
        Rect r = new Rect();
        mViewObserved.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    }

    @Override
    public void onBackPressed() {
        onBack();
    }

    public void onBack() {
        if(ActivityManager.get().getCurrentActivity() instanceof RouterActivity) {
            ((RouterActivity) ActivityManager.get().getCurrentActivity()).pop();
        } else {
            finish();
        }
    }

}
